package com.jy.modules.cims.component.common.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.DictDeatil;
import com.jy.modules.cims.data.common.dao.TCMmCooperorgDao;
import com.jy.modules.cims.data.common.dao.TCMmCreditDetailDao;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.dao.CreditDetailDao;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.QuotaDetailUnlockParamDto;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.platform.sysdict.impl.SysDictAPImpl;
import com.jy.platform.api.sysdict.SysDictDetailVo;
import com.jy.platform.core.common.BaseDTO;

/**
 * @classname: TCMmCreditDetailService
 * @description: 定义 债权明细 实现类
 * @author: zhiqiang
 */
@Service("com.jy.modules.cims.component.common.service.TCMmCreditDetailService")
public class TCMmCreditDetailService {

	@Autowired
	private DictDeatil dict;
	
	@Autowired
	private TCMmCreditDetailDao dao;

	@Autowired
	private CreditDetailDao creditDetailDao;

	@Autowired
	public TCMmCooperorgDao cooperorgDao;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	public IInteractAssist iInteractAssist;

	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
	private ICInteract iCInteract;
	
	@Autowired
	private SysDictAPImpl sysDictAPI;

	/**
	 * @author zhiqiang
	 * @description: 分页查询 债权明细列表
	 * @date 2015-01-07 16:21:37
	 * @param searchParams
	 *            条件
	 * @return
	 * @throws
	 */
	public List<TCMmCreditDetailDTO> searchTCMmCreditDetailByPaging(Map<String, Object> searchParams) throws Exception {
		List<TCMmCreditDetailDTO> dataList = dao.searchTCMmCreditDetailByPaging(searchParams);
		return dataList;
	}
	/**
	 * 
	 * @Title searchCreditPlanRedeemTotalByPaging
	 * @Description TODO
	 * @param searchParams
	 * @return
	 * @throws Exception 
	 * List<TCMmCreditDetailDTO> 
	 * @author lizhiqiang
	 * @date 2016-7-28-下午2:51:09
	 * @update 
	 * @throws
	 */
	public List<TCMmCreditDetailDTO> searchCreditPlanRedeemTotalByPaging(Map<String, Object> searchParams) throws Exception {
		List<TCMmCreditDetailDTO> dataList = dao.searchCreditPlanRedeemTotalByPaging(searchParams);
		return dataList;
	}
	
	public List<TCMmCreditDetailDTO> searchCreditPlanRedeemTotal(Map<String, Object> searchParams) throws Exception {
		List<TCMmCreditDetailDTO> dataList = dao.searchCreditPlanRedeemTotal(searchParams);
		List<TCMmCreditDetailDTO> resultList = new ArrayList<TCMmCreditDetailDTO>();
		for (TCMmCreditDetailDTO tcMmCreditDetailDTO : dataList) {
			tcMmCreditDetailDTO.setCreditorStatus(this.getDictDetailName("creditorStatus", tcMmCreditDetailDTO.getCreditorStatus()));
			resultList.add(tcMmCreditDetailDTO);
		}
		return dataList;
	}

	/**
	 * 数据字典码值取名称
	 * 
	 * @Title getDictDetailName
	 * @Description TODO
	 * @param dict_code
	 * @param detail_value
	 * @return String
	 * @author lizhiqiang
	 * @date 2015-4-9-下午4:40:07
	 * @update
	 * @throws
	 */
	public String getDictDetailName(String dict_code, String detail_value) {
		String dictDetailName = "";
		if (SimpleStringUtils.hasText(dict_code) && SimpleStringUtils.hasText(detail_value)) {
			SysDictDetailVo sysDictDetailVo = sysDictAPI.queryDetailByDictCodeAndDeatailValue(dict_code, detail_value);
			if (sysDictDetailVo != null)
				dictDetailName = sysDictDetailVo.getDictDetailName();
		}
		return dictDetailName;
	}
	/**
	 * @author zhiqiang 
	 * @description: 按条件查询债权明细列表
	 * @date 2015-01-07 16:21:37
	 * @param searchParams
	 *            条件
	 * @return
	 * @throws
	 */
	public List<TCMmCreditDetailDTO> searchTCMmCreditDetail(Map<String, Object> searchParams) throws Exception {
		List<TCMmCreditDetailDTO> dataList = dao.searchTCMmCreditDetail(searchParams);
		return dataList;
	}
	
	
	

	/**
	 * @author zhiqiang
	 * @description: 查询债权明细对象
	 * @date 2015-01-07 16:21:37
	 * @param id
	 * @return
	 * @throws
	 */
	public TCMmCreditDetailDTO queryTCMmCreditDetailByPrimaryKey(String id) throws Exception {

		TCMmCreditDetailDTO dto = dao.findTCMmCreditDetailByPrimaryKey(id);

		if (dto == null)
			dto = new TCMmCreditDetailDTO();

		return dto;

	}

	/**
	 * @title: insertTCMmCreditDetail
	 * @author zhiqiang
	 * @description: 新增 债权明细对象
	 * @date 2015-01-07 16:21:37
	 * @param dto
	 * @return
	 * @throws
	 */
	@SuppressWarnings("all")
	public Long insertTCMmCreditDetail(TCMmCreditDetailDTO dto) throws Exception {
		dto.setCreditorValueUpdateDate(new Date());
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);

		int count = dao.insertTCMmCreditDetail(paramMap);

		TCMmCreditDetailDTO resultDto = (TCMmCreditDetailDTO) paramMap.get("dto");
		Long keyId = resultDto.getId();
		return keyId;
	}

	/**
	 * @title: updateTCMmCreditDetail
	 * @author zhiqiang
	 * @description: 修改 债权明细对象
	 * @date 2015-01-07 16:21:37
	 * @param paramMap
	 * @return
	 * @throws
	 */
	public void updateTCMmCreditDetail(TCMmCreditDetailDTO dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);

		dao.updateTCMmCreditDetail(paramMap);
	}
	
	/**
	 * @title: updateTCMmCreditDetailByTransferId
	 * @description: 通过转让编号更新对象债权明细
	 * @param paramMap
	 * @return
	 * @throws
	 */
	public void updateTCMmCreditDetailByTransferId(TCMmCreditDetailDTO dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);

		dao.updateTCMmCreditDetailByTransferId(paramMap);
	}
	
	/**
	 * 更新债权明细通过条件
	 * @param dto
	 * @throws Exception
	 */
	public void updateTCMmCreditDetailByCondition(TCMmCreditDetailDTO dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", dto);

		dao.updateTCMmCreditDetailByCondition(paramMap);
	}
	
	/**
	 * 
	 * @author zhoup
	 * @description: 根据转让编号更新债权明细表中的包名
	 * @date 2016-07-07 10:21:37
	 * @param dto
	 * @throws Exception
	 */
	public void updateTCMmCreditDetailByPackageNum(String transferId,String PackageNumNew) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		 //根据转让编号更新债权明细表中的包名
        TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
        dto.setTransferId(transferId);
        dto.setPackageNumNew(PackageNumNew);
		paramMap.put("dto", dto);
		paramMap.put("transferId", transferId);
		dao.updateTCMmCreditDetailByPackageNum(paramMap);
	}

	/**
	 * @title: deleteTCMmCreditDetailByPrimaryKey
	 * @author zhiqiang
	 * @description: 删除 债权明细,按主键
	 * @date 2015-01-07 16:21:37
	 * @param paramMap
	 * @throws
	 */
	public void deleteTCMmCreditDetailByPrimaryKey(BaseDTO baseDto, String ids) throws Exception {
		if (SimpleStringUtils.isEmpty(ids))
			throw new Exception("删除失败！传入的参数主键为null");

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("dto", baseDto);
		paramMap.put("ids", ids);
		dao.deleteTCMmCreditDetailByPrimaryKey(paramMap);
	}

	/**
	 * 
	 * @Title searchCreditDetailExportFields
	 * @Description 查询债权导出字段
	 * @param searchParams
	 * @return
	 * @throws Exception
	 *             List<TCMmCreditDetailDTO>
	 * @date 2015-1-22-下午2:56:23
	 * @update
	 * @throws
	 */
	public List<TCMmCreditDetailDTO> searchCreditDetailExportData(Map<String, Object> searchParams) throws Exception {
		List<TCMmCreditDetailDTO> dataList = dao.searchCreditDetailExportData(searchParams);
		return dataList;
	}

	/**
	 * @title: updateTCMmCreditDetailStatus
	 * @author zhuwenbin
	 * @description: 修改 债权状态
	 * @date 2015-02-05 16:21:37
	 * @param paramMap
	 * @return
	 * @throws
	 */
	public void updateTCMmCreditDetailStatus(TCMmCreditDetailDTO dto) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		
		paramMap.put("dto", dto);

		creditDetailDao.updateTCMmCreditDetailStatus(paramMap);
	}
	
	/**
	 * @title: updateTCMmCreditDetailStatus
	 * @description: 修改 账单日
	 * @return
	 * @throws
	 */
	public void updateTCMmCreditDetailBillDate(String transferId,String billDate) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		
		paramMap.put("billDate", billDate);
		
		paramMap.put("transferId", transferId);

		creditDetailDao.updateTCMmCreditDetailBillDate(paramMap);
	}

	/**
	 * @title: updateTCMmCreditDetail
	 * @author zhuwenbin
	 * @description: 批量修改 债权状态
	 * @date 2015-02-05 16:21:37
	 * @param paramMap
	 * @return
	 * @throws
	 */
	public void batchUpdateTCMmCreditStatus(String ids, String status) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("status", status);
		paramMap.put("ids", ids);
		creditDetailDao.batchUpdateTCMmCreditStatus(paramMap);
		List<CreditDetailDto> creditList = searchCreditDetailByIds(ids);
		// 调用释放债权接口
		unlockCreditDetailResult(creditList);

	}

	/**
	 * @author zhuwenbin
	 * @description: 分页查询 债权明细列表
	 * @date 2015-03-05 16:21:37
	 * @param searchParams
	 *            条件
	 * @return
	 * @throws
	 */
	public List<CreditDetailDto> searchCreditDetailByIds(String ids) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ids", ids);
		List<CreditDetailDto> dataList = creditDetailDao.searchCreditDetailByIds(paramMap);
		return dataList;
	}

	/**
	 * @author zhuwenbin
	 * @description: 分页查询 债权明细列表
	 * @date 2015-03-05 16:21:37
	 * @param searchParams
	 *            条件
	 * @return
	 * @throws
	 */
	public List<CreditDetailDto> searchCreditDetailByPaging(Map<String, Object> searchParams) throws Exception {
		List<CreditDetailDto> result = new ArrayList<CreditDetailDto>();
		List<CreditDetailDto> dataList = creditDetailDao.searchCreditDetailByPaging(searchParams);
		if (CollectionsUtils.isNotEmpty(dataList)) {
			TCMmCooperorgDTO cooperorg = null;
			for (CreditDetailDto dto : dataList) {
				cooperorg = new TCMmCooperorgDTO();
				cooperorg.setCooperorgCode(dto.getCooperorgCode());
				List<TCMmCooperorgDTO> cooperorgList = cooperorgDao.searchTCMmCooperorg(SearchParamUtil.getSearchParam(cooperorg));
				if (CollectionsUtils.isNotEmpty(cooperorgList)) {
					dto.setCooperorgName(cooperorgList.get(0).getCooperorgName());
				}
				result.add(dto);
			}
		}
		return result;
	}
	
	/**
	 * @author zhoupeng
	 * @description: 债权明细列表 导出查询
	 * @date 2015-11-02 16:21:37
	 * @param searchParams
	 *            条件
	 * @return
	 * @throws
	 */
	public List<CreditDetailDto> searchTCMmCreditDetailExport(Map<String, Object> searchParams) throws Exception {

		List<CreditDetailDto> dataList = creditDetailDao.searchTCMmCreditDetailExport(searchParams);
		String[] columnCodes = new String[] {"creditorStatus" ,"cooperorgCodes","abnormalSettle","product_type","CM_REPAYMENTWAY","coreCreditorStatus","LOAN_EACH_STATUS","CREDIT_SOURCE"}; 
		Map<String, Map> excelColumnsConvertMap = dict.queryDictDetailByTempalteMap(columnCodes);
        List<CreditDetailDto> loanDetaillist = new ArrayList<CreditDetailDto>();
        for (CreditDetailDto credDetailDto : dataList) {
        	if(isEmptyString(excelColumnsConvertMap,"creditorStatus",credDetailDto.getCreditorStatus()))
        	credDetailDto.setCreditorStatusName(excelColumnsConvertMap.get("creditorStatus").get(credDetailDto.getCreditorStatus()).toString());// 债权状态 
        	
        	if(isEmptyString(excelColumnsConvertMap,"cooperorgCodes",credDetailDto.getCooperorgCode()))
        	credDetailDto.setCooperorgName(excelColumnsConvertMap.get("cooperorgCodes").get(credDetailDto.getCooperorgCode()).toString());// 合作机构
        	
        	if(isEmptyString(excelColumnsConvertMap,"product_type",credDetailDto.getProductType()))
        	credDetailDto.setProductType(excelColumnsConvertMap.get("product_type").get(credDetailDto.getProductType()).toString());// 产品类型
        	
        	if(isEmptyString(excelColumnsConvertMap,"CM_REPAYMENTWAY",credDetailDto.getRepayType()))
        	credDetailDto.setRepayType(excelColumnsConvertMap.get("CM_REPAYMENTWAY").get(credDetailDto.getRepayType()).toString());// 还款方式 
        	
        	if(isEmptyString(excelColumnsConvertMap,"CREDIT_SOURCE",credDetailDto.getCreditSource()))
        	credDetailDto.setCreditSource(excelColumnsConvertMap.get("CREDIT_SOURCE").get(credDetailDto.getCreditSource()).toString());// 债权来源
        	
        	if(isEmptyString(excelColumnsConvertMap,"coreCreditorStatus",credDetailDto.getCoreState()))
        	credDetailDto.setCoreState(excelColumnsConvertMap.get("coreCreditorStatus").get(credDetailDto.getCoreState()).toString());// 核心债权状态 
        	
        	if(isEmptyString(excelColumnsConvertMap,"LOAN_EACH_STATUS",credDetailDto.getCreditEachStatus()))
        	credDetailDto.setCreditEachStatus(excelColumnsConvertMap.get("LOAN_EACH_STATUS").get(credDetailDto.getCreditEachStatus()).toString());// 债权交互状态
        	if(SimpleStringUtils.hasText(credDetailDto.getAbnormalStatus()) && SimpleStringUtils.hasText(credDetailDto.getAbnormalStatus()))
        	{
        		credDetailDto.setAbnormalStatusName(excelColumnsConvertMap.get("abnormalSettle").get(credDetailDto.getAbnormalStatus()).toString());// 异常状态
        	}
            loanDetaillist.add(credDetailDto);
        }
        return loanDetaillist;
	}
	
	public boolean isEmptyString(Map<String, Map> excelColumnsConvertMap, String key,String value){
		if(null == value){
			return false;
		}else if(null == excelColumnsConvertMap.get(key).get(value)){
			return false;
		}else {
			return true;
		}
				
	}

	public void unlockCreditDetailResult(List<CreditDetailDto> creditDetailList) throws Exception {
		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();

		List<QuotaDetailUnlockParamDto.CreditRightUnlockInfo> creditRightUnlockInfoList = new ArrayList<QuotaDetailUnlockParamDto.CreditRightUnlockInfo>();
		for (CreditDetailDto creditDetailDto : creditDetailList) {
			if (CimsConstant.CREDIT_STATUS_WAY.equals(creditDetailDto.getCreditorStatus())) {
				QuotaDetailUnlockParamDto.CreditRightUnlockInfo creditRightUnlockInfo = new QuotaDetailUnlockParamDto.CreditRightUnlockInfo();
				creditRightUnlockInfo.setCreditId(creditDetailDto.getCreditCode());// 债权编号
				creditRightUnlockInfo.setTransferId(creditDetailDto.getTransferId());// 转让编号
				creditRightUnlockInfo.setEachRepaymentValue(creditDetailDto.getThisRepaySum());// //本次释放对应月还金额(本期还款金额)
				creditRightUnlockInfo.setFreeValue(creditDetailDto.getThisMakeCreditorValue());// 本次释放债权价值（本次转让债权价值）
				creditRightUnlockInfoList.add(creditRightUnlockInfo);
			}
		}

		if (creditRightUnlockInfoList.size() > 0) {
			QuotaDetailUnlockParamDto paramDto = new QuotaDetailUnlockParamDto();
			paramDto.setQuotaType(CimsConstant.QUOTATYPE_CR);
			paramDto.setCreditRightUnlockList(creditRightUnlockInfoList);
			paramDto.setDealCode(busiNoForInteract);
			// 调用释放债权的接口
			iCInteract.quotaDetailUnlock(paramDto);
		}
	}
}
